import 'dart:async';

import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:ls_work/common/common.dart';
import 'package:ls_work/widgets/app_bar.dart';
import 'package:webview_flutter/webview_flutter.dart';
// #docregion platform_imports
// Import for Android features.
import 'package:webview_flutter_android/webview_flutter_android.dart';
// Import for iOS features.
import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart';

class WebViewPage extends StatefulWidget {
   WebViewPage({
    Key? key,
    required this.title,
    required this.url,
    this.isLocal = false
  }) : super(key: key);

  final String title;
  final String url;
  bool isLocal;

  @override
  _WebViewPageState createState() => _WebViewPageState();
}

class _WebViewPageState extends State<WebViewPage> {
  // final Completer<WebViewController> _controller = Completer<WebViewController>();

  late WebViewController _controller;
  // On urlChanged stream
  StreamSubscription<String>? _onUrlChanged;
  String? _cookie;

  String webViewTitle = "";

  @override
  void initState()  {
    super.initState();
    webViewTitle = widget.title;
    _cookie = SpUtil.getString(Constant.cookie);
    // print("🍎 - ${SpUtil.getString(Constant.cookie)}");
    // #docregion platform_features
    initWeb();
    request();
  }

  Future<void> request() async {
    _controller.clearCache();
    if(widget.isLocal){
      // String fileText = await rootBundle.loadString(widget.url);
      _controller.loadFlutterAsset(widget.url);
    }else{
      _controller.loadRequest(Uri.parse(widget.url),headers: {
        "Cookie": "JSESSIONID=$_cookie",
        "client-type": "1",
      });
    }
  }

  void initWeb()  {
    late final PlatformWebViewControllerCreationParams params;
    if (WebViewPlatform.instance is WebKitWebViewPlatform) {
      params = WebKitWebViewControllerCreationParams(
        allowsInlineMediaPlayback: true,
        mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{},
      );
    } else {
      params = const PlatformWebViewControllerCreationParams();

    }

    final WebViewController controller =
    WebViewController.fromPlatformCreationParams(params);
    // #enddocregion platform_features

    controller
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(const Color(0x00000000))
      ..addJavaScriptChannel(
        'Toaster',
        onMessageReceived: (JavaScriptMessage message) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text(message.message)),
          );
        },
      )
    ..addJavaScriptChannel('PrintTitle', onMessageReceived: (JavaScriptMessage message){
      String title = message.message;
      setState(() {
        webViewTitle = title;
      });
    },)
    ..setNavigationDelegate(NavigationDelegate(
      onPageFinished: (url){
        controller.runJavaScript('''
              PrintTitle.postMessage(document.title);
            ''');
      }
    ));




    // #docregion platform_features
    if (controller.platform is AndroidWebViewController) {
      AndroidWebViewController.enableDebugging(true);
      (controller.platform as AndroidWebViewController)
          .setMediaPlaybackRequiresUserGesture(false);
    }
    // #enddocregion platform_features
    _controller = controller;
  }

  @override
  void dispose() async {
    super.dispose();
    // flutterWebViewPlugin.close();
    // _controller.
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(child: Scaffold(
      appBar: AppBar(
        title: Text(webViewTitle),
        centerTitle: true,
        elevation: 0.5,
      ),
      body: WebViewWidget(controller: _controller,),
    ),onPopInvoked: (didPop) async {
      if(await _controller.canGoBack()){
        await _controller.goBack();
      }else{
        if(!didPop){
          Navigator.of(context).pop();
        }
      }
    },canPop: false,);
    // return WebviewScaffold(
    //   url: widget.url,
    //   clearCache: true,
    //   clearCookies: true,
    //   withZoom: true,
    //   withLocalStorage: true,
    //   hidden: true,
    //   withJavascript: true,
    //   headers: {
    //     "Cookie": "JSESSIONID=$_cookie",
    //     "client-type": "1",
    //   },
    //   appBar: AppBar(
    //     title: Text("${widget.title}"),
    //     centerTitle: true,
    //     elevation: 0.5,
    //   ),
    // );
    // return FutureBuilder<WebViewController>(
    //     future: _controller.future,
    //     builder: (context, snapshot) {
    //       return WillPopScope(
    //         onWillPop: () async {
    //           if (snapshot.hasData) {
    //             bool canGoBack = await snapshot.data.canGoBack();
    //             if (canGoBack) {
    //               // 网页可以返回时，优先返回上一页
    //               snapshot.data.goBack();
    //               return Future.value(false);
    //             }
    //             return Future.value(true);
    //           }
    //           return Future.value(true);
    //         },
    //         child: Scaffold(
    //             appBar: MyAppBar(
    //               centerTitle: widget.title,
    //             ),
    //             body: WebView(
    //               initialUrl: widget.url,
    //               javascriptMode: JavascriptMode.unrestricted,
    //               onWebViewCreated: (WebViewController webViewController) {
    //                 _controller.complete(webViewController);
    //               },
    //             )),
    //       );
    //     });
  }


}
